<template>
  <view class="payment-container">
    <!-- 房东信息 -->
    <view class="info-section">
      <view class="section-title">
        <text class="section-title-text">房东信息</text>
        <text class="required">*</text>
      </view>
      <view class="input-item">
        <text class="label">姓名</text>
        <input class="input" :value="'***'" placeholder="请选择房东" disabled />
      </view>
      <view class="input-item">
        <text class="label">手机号</text>
        <text class="input">{{ maskPhone(formData.phone) || '房东手机号' }}</text>
      </view>
    </view>

    <!-- 缴费地址（多地址支持） -->
    <view v-for="(item, idx) in formData.addressList" :key="idx">
      <view v-if="idx > 0" class="address-divider"></view>
      <view class="info-section">
        <view class="section-title">
          <text class="section-title-text">缴费地址{{ idx + 1 }}</text>
          <text class="close-icon" v-if="formData.addressList.length > 1" @click="removeAddress(idx)">×</text>
        </view>
        <view class="input-item arrow-item">
          <text class="label required">选择地址</text>
          <view class="right-content">
            <view class="address-ellipsis" @click="openAddressPicker(idx)"
              @longpress="showFullAddress(item.fullAddress)">
              <text class="placeholder" v-if="!item.fullAddress">请选择省市区镇村/门牌</text>
              <text v-else>{{ item.fullAddress }}</text>
            </view>
            <text class="edit-btn" @click="openAddressPicker(idx)">编辑</text>
          </view>
        </view>
        <view v-if="item.noAddress" class="no-address-tip">
          未找到您的地址？请拨打客服电话：<text class="phone">400-xxxx-xxxx</text>
        </view>
        <!-- 是否公安开关 -->
        <view class="input-item">
          <text class="label">是否公安</text>
          <switch :checked="item.isPolice" @change="onPoliceSwitch($event, idx)" />
        </view>
        <!-- 只有未公安时才显示套餐选择 -->
        <view v-if="!item.isPolice">
          <view class="plan-section">
            <view class="section-title">
              <text class="section-title-text">选择方案(单选)</text>
            </view>
            <view class="plan-group">
              <!-- 显示方案列表，根据是否有地址信息显示不同的价格 -->
              <view v-for="plan in planList" :key="plan.id" class="plan-item" :class="{ active: item.plan == plan.id }"
                @click="selectPlan(plan.id, idx)">
                <view class="plan-checkbox">
                  <view class="checkbox-inner" v-if="item.plan == plan.id"></view>
                </view>
                <view class="plan-content">
                  <view class="plan-name">{{ plan.name }}
                    <text class="plan-tag" :class="{ 'plan-tag-highlight': plan.tag1 === '含抓拍枪' }" v-if="plan.tag1">({{
                      plan.tag1 }})</text>
                    <text class="recommend-tag" v-if="plan.tag2 === '推荐'">荐</text>
                  </view>
                  <view class="plan-desc">{{ plan.desc1 }}</view>
                  <view class="plan-desc">{{ plan.desc2 }}</view>
                  <!-- 如果有地址的运维费信息，显示运维费详情 -->
                  <view v-if="item.monthPrice" class="plan-desc plan-gift">
                    运维费：¥{{ Number(item.monthPrice).toFixed(2) }}/月 × {{ item.maintenanceDuration || 1 }}年
                  </view>
                  <!-- 显示费用明细（安装费+抓拍枪费） -->
                  <view v-if="item.monthPrice && getCurrentPlanInfo(item, idx)" class="plan-desc">
                    {{ getFeeBreakdownText(getCurrentPlanInfo(item, idx)) }}
                  </view>
                  <!-- 显示匹配的方案信息 -->
                  <view v-if="item.monthPrice && getCurrentPlanInfo(item, idx)" class="plan-desc plan-gift">
                    方案：{{ getCurrentPlanInfo(item, idx).name }} ({{ getCurrentPlanInfo(item, idx).installType }})
                  </view>
                </view>
                <!-- 使用新的价格计算逻辑 -->
                <view class="plan-price">
                  <template v-if="item.monthPrice">
                    {{ calculateNewPlanTotalPrice(item, idx) }}元
                  </template>
                  <template v-else>
                    {{ plan.price.toFixed(2) }}元
                  </template>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 年份选择区域 - 一行背景框版 -->
        <view v-if="item.monthPrice && item.plan" style="margin: 20rpx; padding: 0;">
          <view style="background: #ffffff; border: 2rpx solid #f0f0f0; border-radius: 16rpx; padding: 24rpx; box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);">
            <text style="font-size: 28rpx; font-weight: 600; color: #333; display: block; margin-bottom: 16rpx;">缴费年限</text>
            
            <!-- 一行四个按钮的美化版本 -->
            <view style="background: #f8f9fa; border-radius: 16rpx; padding: 12rpx; display: flex; flex-wrap: wrap; gap: 8rpx;">
              <view v-for="option in (idx < formData.addressList.length ? getAvailableYearsForAddress(idx) : durationOptions)" 
                    :key="option.years + '_' + (option.installType || 'default')"
                    :style="{
                      flex: '1 1 calc(25% - 6rpx)',
                      minWidth: '0',
                      maxWidth: 'calc(25% - 6rpx)',
                      padding: '20rpx 8rpx',
                      borderRadius: '12rpx',
                      textAlign: 'center',
                      border: '2rpx solid',
                      borderColor: isYearOptionSelected(item, option) ? '#1989fa' : '#e8e8e8',
                      background: isYearOptionSelected(item, option) ? 'linear-gradient(135deg, #1989fa 0%, #0d7fe8 100%)' : '#ffffff',
                      boxShadow: isYearOptionSelected(item, option) ? '0 6rpx 12rpx rgba(25, 137, 250, 0.3)' : '0 2rpx 6rpx rgba(0,0,0,0.08)',
                      transform: isYearOptionSelected(item, option) ? 'translateY(-2rpx)' : 'none',
                      transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                      boxSizing: 'border-box'
                    }"
                    @click="selectMaintenanceDurationWithType(idx, option)">
                <text :style="{
                  fontSize: '24rpx',
                  color: isYearOptionSelected(item, option) ? '#ffffff' : '#333',
                  fontWeight: isYearOptionSelected(item, option) ? '600' : '500',
                  lineHeight: '1.3',
                  display: 'block',
                  wordBreak: 'keep-all',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }">
                  {{ option.label }}
                </text>
              </view>
            </view>
          </view>
        </view>


        <!-- 其他费用始终显示 -->
        <view class="other-fee-section">
          <view class="section-title">
            <text class="section-title-text">其他费用</text>
          </view>
          <view class="input-item">
            <text class="label">工程金额/元</text>
            <input class="input" placeholder="请输入金额" v-model="item.engineeringFee" type="digit" />
          </view>
        </view>
      </view>
    </view>
    <view class="add-address-btn" @click="addAddress">
      <text class="add-icon">+</text>
      <text>添加新地址</text>
    </view>

    <!-- 底部结算 -->
    <view class="footer">
      <view class="total-section total-section-vertical">
        <text>合计：{{ formData.addressList.length }}个地址</text>
        <text class="total-price">{{ totalPrice }}元</text>
      </view>
      <view class="confirm-btn" :class="{ loading: isPaying }" @click="confirmPayment">
        <text v-if="isPaying">缴费中...</text>
        <text v-else>确认缴费</text>
      </view>
    </view>

    <!-- 微信风格地址选择弹窗 -->
    <uni-popup ref="addressPopup" type="bottom">
      <view class="wx-popup-content">
        <view class="wx-popup-tabs">
          <view :class="['wx-tab', popupTab === 0 ? 'active' : '']" @click="popupTab = 0">地址选择</view>
          <view :class="['wx-tab', popupTab === 1 ? 'active' : '']" @click="popupTab = 1">房东选择</view>
        </view>
        <view v-if="popupTab === 0">
          <view class="wx-popup-header">
            <view v-if="deptPath.length > 0" class="wx-back-btn" @click="goBackDept"><text
                class="wx-back-arrow">←</text></view>
            <view class="wx-breadcrumb">
              <text v-for="(item, idx) in deptPath" :key="item.id" class="wx-breadcrumb-item" @click="goToDept(idx)">{{
                item.label }}</text>
            </view>
          </view>
          <view class="wx-popup-title">选择地址</view>
          <view class="wx-list-wrap">
            <view v-for="item in filteredDeptList" :key="item.id" class="wx-list-item"
              :class="{ active: isDeptActive(item) }" @click="onDeptSelect(item)">
              <text>{{ highlightKeyword(item.label, searchKeyword) }}</text>
              <text v-if="item.children && item.children.length" class="wx-arrow">›</text>
            </view>
          </view>
          <view v-if="showHouseList || filteredHouseList.length > 0">
            <view class="wx-popup-title-sub wx-blue-bar">房产地址</view>
            <view class="wx-search-input">
              <view class="search-input-wrapper">
                <uni-icons type="search" size="16" color="#999"></uni-icons>
                <input class="house-search-input" v-model="houseSearchKeyword" placeholder="请输入业主姓名、门禁编码等关键词搜索"
                  @input="onHouseSearch" @focus="onHouseSearchFocus" @blur="onHouseSearchBlur" />
                <text v-if="houseSearchKeyword" class="clear-btn" @click="clearHouseSearch">×</text>
              </view>
            </view>
            <view class="wx-list-wrap">
              <view v-for="house in filteredHouseList" :key="house.id" class="wx-list-item"
                @click="onHouseSelect(house)">
                <text class="wx-address-text">{{ getFullDeptNameByIds(house) }}/{{ house.address }}</text>
              </view>
            </view>
            <view v-if="filteredHouseList.length === 0" class="no-address-tip">
              <view class="no-address-content">
                <uni-icons type="info" size="16" color="#ff6b6b"></uni-icons>
                <text class="no-address-text">未找到您的地址？</text>
              </view>
              <view class="contact-info">
                <text class="contact-label">请拨打客服电话：</text>
                <text class="phone-number" @click="callService">4006983338</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else>
          <view class="wx-popup-title">房东选择</view>
          <view class="wx-landlord-switch">
            <uni-easyinput v-model="landlordSearch" placeholder="输入姓名/手机号搜索" @input="onLandlordInput"
              @change="onLandlordInput" :clearable="true" />
          </view>
          <view class="wx-list-wrap" style="margin-top: 4px;">
            <view v-if="landlordSearchLoading" class="wx-search-tip">
              正在搜索房东...
            </view>
            <view v-else-if="!landlordSearch && !hasSearched" class="wx-search-tip">
              请输入房东姓名或手机号进行搜索
            </view>
            <view v-else-if="landlordSearch && hasSearched && displayedLandlords.length === 0" class="wx-search-tip">
              未找到匹配的房东，请尝试其他关键词
            </view>
            <view v-for="landlord in displayedLandlords" :key="landlord.userId" class="wx-list-item wx-list-item-blue"
              @click="onLandlordSelect(landlord)">
              <text>{{ maskName(landlord.nickName || landlord.nickName) }}（{{ maskPhone(landlord.phonenumber) }}）</text>
            </view>
          </view>
          <view v-if="showHouseList">
            <view class="wx-popup-title-sub wx-blue-bar">房产地址</view>
            <view class="wx-search-input">
              <view class="search-input-wrapper">
                <uni-icons type="search" size="16" color="#999"></uni-icons>
                <input class="house-search-input" v-model="houseSearchKeyword" placeholder="请输入业主姓名、门禁编码等关键词搜索"
                  @input="onHouseSearch" @focus="onHouseSearchFocus" @blur="onHouseSearchBlur" />
                <text v-if="houseSearchKeyword" class="clear-btn" @click="clearHouseSearch">×</text>
              </view>
            </view>
            <view class="wx-list-wrap">
              <view v-for="house in filteredHouseList" :key="house.id" class="wx-list-item"
                @click="onHouseSelect(house)">
                <text class="wx-address-text">{{ getFullDeptNameByIds(house) }}/{{ house.address }}</text>
              </view>
            </view>
            <view v-if="filteredHouseList.length === 0" class="no-address-tip">
              <view class="no-address-content">
                <uni-icons type="info" size="16" color="#ff6b6b"></uni-icons>
                <text class="no-address-text">未找到您的地址？</text>
              </view>
              <view class="contact-info">
                <text class="contact-label">请拨打客服电话：</text>
                <text class="phone-number" @click="callService">4006983338</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import request from '@/utils/request';
import { addOrderInfo } from '@/api/login';

export default {
  data() {
    return {
      formData: {
        name: '',
        phone: '',
        addressList: [
          {
            province: '',
            city: '',
            district: '',
            street: '',
            village: '',
            addressId: '',
            fullAddress: '',
            noAddress: false,
            chCardNo: '',
            plan: '',
            engineeringFee: '',
            isPolice: false,
            monthPrice: 0,
            installPrice: 0,
            cardPrice: 0,
            giftMonthOfByOneYear: 0,
            maintenanceDuration: 1,
            installPriceList: []
          }
        ],
        isPolice: false
      },
      planList: [],
      // 新增方案数据配置
      planOptions: [
        {"name":"方案1","monthlyRent":35,"installType":"升级","years":"1年","installFee":150,"poleFee":0,"price":150},
        {"name":"方案2","monthlyRent":35,"installType":"升级","years":"2年","installFee":0,"poleFee":0,"price":0},
        {"name":"方案3","monthlyRent":55,"installType":"升级","years":"2年","installFee":0,"poleFee":0,"price":0},
        {"name":"方案4","monthlyRent":35,"installType":"新装","years":"2年","installFee":150,"poleFee":0,"price":150},
        {"name":"方案5","monthlyRent":55,"installType":"新装","years":"1年","installFee":0,"poleFee":300,"price":300},
        {"name":"方案6","monthlyRent":55,"installType":"新装","years":"2年","installFee":0,"poleFee":150,"price":150}
      ],
      filteredPlanOptions: [], // 根据月租过滤后的方案
      availableYears: [], // 可选年份
      deptTree: [], // 省市区县镇村树
      deptPath: [], // 当前选择路径
      currentDeptList: [], // 当前展示的子节点
      searchKeyword: '',
      filteredDeptList: [],
      showHouseList: false,
      houseList: [],
      houseSearchKeyword: '',
      filteredHouseList: [],
      addressPickerIdx: 0, // 当前操作的地址下标
      showCustomPopup: false,
      isPaying: false,
      landlordId: '',
      landlordOptions: [],
      allLandlords: [],
      popupTab: 0,
      landlordSearch: '',
      filteredLandlords: [],
      openid: '',
      showLandlordsLimit: 3,
      jiamiphone: '',
      // 新增搜索相关状态
      landlordSearchLoading: false,
      landlordSearchDebounceTimer: null,
      hasSearched: false,
      // 运维费年份选项配置
      durationOptions: [
        { years: 1, label: '一年' },
        { years: 2, label: '两年' },
        { years: 3, label: '三年' },
        { years: 5, label: '五年' }
      ],
      currentSelectedPlan: null // 当前选择的方案对象
    }
  },
  computed: {
    totalPrice() {
      let price = 0;
      this.formData.addressList.forEach(item => {
        // 计算总价格：公安类型只计算工程费用，非公安类型计算运维费+安装费+工程费用
        if (!item.isPolice) {
          // 使用新的计算逻辑：月租 * 12 * 年份 + price（安装费+拍杆费）
          if (item.monthPrice && !isNaN(item.monthPrice)) {
            const duration = item.maintenanceDuration || 1;
            const monthlyRent = parseFloat(item.monthPrice);
            const maintenanceTotal = monthlyRent * 12 * duration; // 运维费总额
            
            // 获取对应的方案price（安装费+拍杆费）
            const yearsStr = duration === 1 ? '1年' : '2年';
            const selectedInstallType = item.selectedInstallType;
            // 优先使用接口返回的方案数据
            const planDataSource = item.planOptionsFromApi && item.planOptionsFromApi.length > 0 
              ? item.planOptionsFromApi 
              : this.planOptions;
            const matchedPlan = planDataSource.find(plan => {
              const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
              const matchesRentAndYear = planMonthlyRent === monthlyRent && plan.years === yearsStr;
              
              // 如果有选中的安装类型，也要匹配
              if (selectedInstallType) {
                return matchesRentAndYear && plan.installType === selectedInstallType;
              }
              
              return matchesRentAndYear;
            });
            const planPrice = matchedPlan ? matchedPlan.price : 0;
            
            console.log('totalPrice计算 - 月租:', monthlyRent, '年份:', duration, '安装类型:', selectedInstallType, '匹配方案:', matchedPlan, '运维费:', maintenanceTotal, '安装费:', planPrice);
            
            price += maintenanceTotal + planPrice;
          } else if (item.plan) {
            const plan = this.planList.find(p => p.id == item.plan);
            if (plan) price += Number(plan.price);
          }
        }
        // 添加工程费
        if (item.engineeringFee && !isNaN(item.engineeringFee)) {
          price += parseFloat(item.engineeringFee);
        }
      });
      return price.toFixed(2);
    },

    // 显示的房东列表（限制数量或搜索结果）
    displayedLandlords() {
      // 如果正在搜索，显示搜索结果
      if (this.landlordSearch && this.hasSearched) {
        return this.filteredLandlords;
      }
      // 如果没有搜索关键词且没有进行过搜索，显示提示信息
      if (!this.landlordSearch && !this.hasSearched) {
        return [];
      }
      // 其他情况显示过滤后的结果
      return this.filteredLandlords;
    }
  },
  methods: {
    addAddress() {
      this.formData.addressList.push({
        province: '', city: '', district: '', street: '', village: '', addressId: '', fullAddress: '', noAddress: false,
        plan: '',
        engineeringFee: '',
        isPolice: false,
        monthPrice: 0,
        installPrice: 0,
        cardPrice: 0,
        giftMonthOfByOneYear: 0,
        maintenanceDuration: 1,
        installPriceList: []
      });
      // 自动弹出选择弹窗
      this.$nextTick(() => {
        this.openAddressPicker(this.formData.addressList.length - 1);
      });
    },
    removeAddress(idx) {
      this.formData.addressList.splice(idx, 1);
      // 删除后自动更新缓存（由watch自动完成）
    },
    async openAddressPicker(idx) {
      console.log('打开地址选择器，索引:', idx);
      this.addressPickerIdx = idx;
      this.deptPath = [];
      this.searchKeyword = '';
      this.houseSearchKeyword = '';
      this.landlordSearch = ''; // 清空房东搜索关键词
      this.showHouseList = false;
      this.currentDeptList = this.deptTree.length ? this.deptTree[0].children : [];
      this.filteredDeptList = this.currentDeptList;

      // 清空房东相关状态
      this.filteredLandlords = [];
      this.hasSearched = false;
      this.landlordSearchLoading = false;

      this.popupTab = 0;
      this.$nextTick(() => {
        this.$refs.addressPopup.open();
      });
    },
    closeAddressPopup() {
      this.$refs.addressPopup.close();
      this.searchKeyword = '';
      this.houseSearchKeyword = '';
      this.showHouseList = false;
      this.deptPath = [];
      this.currentDeptList = [];
      this.filteredDeptList = [];
      this.houseList = [];
      this.filteredHouseList = [];
    },
    goBackDept() {
      if (this.deptPath.length > 0) {
        this.deptPath.pop();
        if (this.deptPath.length === 0) {
          this.currentDeptList = this.deptTree.length ? this.deptTree[0].children : [];
        } else {
          this.currentDeptList = this.deptPath[this.deptPath.length - 1].children || [];
        }
        this.filteredDeptList = this.currentDeptList;
        this.searchKeyword = '';
      }
    },
    goToDept(idx) {
      this.deptPath = this.deptPath.slice(0, idx + 1);
      this.currentDeptList = this.deptPath[idx].children || [];
      this.filteredDeptList = this.currentDeptList;
      this.searchKeyword = '';
    },
    isDeptActive(item) {
      return this.deptPath.length && this.deptPath[this.deptPath.length - 1].id === item.id;
    },
    onDeptSelect(item) {
      // 只在进入下一级时push，末级节点不push
      if (item.children && item.children.length) {
        this.deptPath.push(item);
        this.currentDeptList = item.children;
        this.filteredDeptList = this.currentDeptList;
        this.searchKeyword = '';
      } else {
        // 末级节点（如镇），只保留一个，不重复push
        if (!this.deptPath.length || this.deptPath[this.deptPath.length - 1].id !== item.id) {
          // 如果当前路径的最后一个节点也是叶子节点（没有children），先移除它
          if (this.deptPath.length && 
              (!this.deptPath[this.deptPath.length - 1].children || 
               this.deptPath[this.deptPath.length - 1].children.length === 0)) {
            this.deptPath.pop();
          }
          this.deptPath.push(item);
        }
        this.fetchHouseList(item.id);
      }
    },
    onSearchInput() {
      if (!this.searchKeyword) {
        this.filteredDeptList = this.currentDeptList;
      } else {
        this.filteredDeptList = this.recursiveFilter(this.currentDeptList, this.searchKeyword);
      }
    },
    recursiveFilter(list, keyword) {
      const res = [];
      for (const item of list) {
        if (item.label.includes(keyword)) {
          res.push(item);
        } else if (item.children && item.children.length) {
          const children = this.recursiveFilter(item.children, keyword);
          if (children.length) {
            res.push({ ...item, children });
          }
        }
      }
      return res;
    },
    highlightKeyword(label, keyword) {
      if (!keyword) return label;
      return label.replace(new RegExp(keyword, 'g'), `<span style="color:#07c160">${keyword}</span>`);
    },
    async fetchHouseList(deptId) {
      try {
        const landlordId = this.landlordId || 1;
        const res = await request({
          url: '/door/house/list',
          method: 'get',
          params: { pageNum: 1, pageSize: 7000, deptId }
        });
        if (res.code === 200 && res.rows) {
          this.houseList = res.rows;
          this.filteredHouseList = this.houseList;
          console.log('获取房产列表成功:', this.houseList.length, '条');
          // 自动填充房东信息（只取第一个地址的房东信息）
          if (res.rows.length > 0) {
            const first = res.rows[0];
            if (first.landlordName) this.formData.name = first.landlordName;
            if (first.landlordPhone) this.formData.phone = first.landlordPhone;
          }
        } else {
          this.houseList = [];
          this.filteredHouseList = [];
          console.log('获取房产列表失败:', res.msg);
        }
      } catch (e) {
        console.error('获取房产列表异常:', e);
        this.houseList = [];
        this.filteredHouseList = [];
      }
      this.showHouseList = true;
    },
    onHouseSearch(e) {
      const keyword = e.detail.value || this.houseSearchKeyword;
      this.houseSearchKeyword = keyword;

      if (!keyword.trim()) {
        this.filteredHouseList = this.houseList;
        return;
      }

      // 模糊搜索房产地址
      this.filteredHouseList = this.houseList.filter(house => {
        const searchText = keyword.toLowerCase();
        const houseText = `${house.address || ''} ${house.door || ''} ${house.ownerName || ''}`.toLowerCase();
        return houseText.includes(searchText);
      });
    },
    async onHouseSelect(house) {
      const fullAddress = this.getFullDeptNameByIds(house) + '/' + house.address;
      
      // 获取该地址的价格信息（使用镇街ID）
      let priceData = null;
      if (house.street) {
        priceData = await this.fetchAddressPrice(house.street);
      }

      const newAddressData = {
        ...this.formData.addressList[this.addressPickerIdx],
        addressId: house.id,
        fullAddress,
        province: house.province,
        city: house.city,
        district: house.district,
        street: house.street,
        village: house.village,
        door: house.door,
        noAddress: false,
        monthPrice: house.monthPrice || 0, // 运维费
        // 安装费先设置为0，会在年限选择时重新计算
        installPrice: 0,
        cardPrice: priceData ? (priceData.cardPrice || 0) : 0,
        giftMonthOfByOneYear: priceData ? (priceData.giftMonthOfByOneYear || 0) : 0,
        maintenanceDuration: 1, // 默认选择一年
        // 保存安装费列表用于后续计算
        installPriceList: priceData ? (priceData.installPriceList || []) : [],
        // 保存接口返回的方案数据
        planOptionsFromApi: priceData && priceData.installPrice ? this.parseInstallPriceData(priceData.installPrice) : [],
        // 保持原有的方案选择状态
        plan: this.formData.addressList[this.addressPickerIdx].plan || ''
      };
      
      // 一次性设置所有地址信息，包括价格信息
      this.$set(this.formData.addressList, this.addressPickerIdx, newAddressData);
      
      // 输出调试信息
      if (priceData && priceData.installPrice) {
        console.log('接口返回的方案数据:', priceData.installPrice);
        console.log('解析后的方案数据:', newAddressData.planOptionsFromApi);
      }
      
      // 立即计算默认1年的安装费
      if (priceData && priceData.installPriceList) {
        const defaultInstallPrice = this.getInstallPriceByYears(priceData.installPriceList, 1);
        this.$set(this.formData.addressList[this.addressPickerIdx], 'installPrice', defaultInstallPrice);
        console.log(`地址选择完成 - 运维费：${house.monthPrice}元/月，默认1年安装费：${defaultInstallPrice}元`);
      }

      // 回填房东信息到页面顶部
      if (house.landlordName) {
        this.formData.name = house.landlordName;
      }
      if (house.landlordPhone) {
        this.formData.phone = house.landlordPhone;
      }

      // 根据运维费匹配可用方案
      this.updateAvailablePlans(this.addressPickerIdx);
      
      // 强制更新视图以显示新的方案信息
      this.$forceUpdate();
      
      this.closeAddressPopup();
    },
    async getDeptTree() {
      try {
        const res = await request({ url: '/system/user/deptTreeNoDataScope', method: 'get' });
        if (res.code === 200 && res.data && res.data.length) {
          this.deptTree = res.data;
        } else {
          this.deptTree = [];
        }
      } catch (e) {
        this.deptTree = [];
      }
    },
    selectPlan(planId, idx) {
      this.$set(this.formData.addressList[idx], 'plan', planId);
      
      // 选择方案后，如果有地址信息，重新计算安装费
      const addressItem = this.formData.addressList[idx];
      if (addressItem.monthPrice && addressItem.installPriceList && Array.isArray(addressItem.installPriceList)) {
        const duration = addressItem.maintenanceDuration || 1;
        const installPrice = this.getInstallPriceByYears(addressItem.installPriceList, duration);
        this.$set(this.formData.addressList[idx], 'installPrice', installPrice);
        console.log(`选择方案${planId}，当前${duration}年安装费：${installPrice}元`);
      }
    },
    selectMaintenanceDuration(idx, duration) {
      this.$set(this.formData.addressList[idx], 'maintenanceDuration', duration);
      
      // 使用新的方案匹配逻辑
      this.updatePlanPrice(idx, duration);
      
      // 强制更新视图以重新计算所有方案的价格显示
      this.$forceUpdate();
    },
    showFullAddress(addr) {
      if (addr) {
        uni.showModal({
          title: '完整地址',
          content: addr,
          showCancel: false
        });
      }
    },
    async confirmPayment() {
      if (this.isPaying) return;
      // 校验姓名
      if (!this.formData.name) {
        return uni.showToast({ title: '请输入姓名', icon: 'none' });
      }
      // 校验手机号
      if (!this.formData.phone) {
        return uni.showToast({ title: '请输入手机号', icon: 'none' });
      }
      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        return uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
      }
      // 校验多地址
      if (!this.formData.addressList.length) {
        return uni.showToast({ title: '请添加至少一个缴费地址', icon: 'none' });
      }
      for (let i = 0; i < this.formData.addressList.length; i++) {
        const addr = this.formData.addressList[i];
        if (!addr.fullAddress || !addr.addressId) {
          return uni.showToast({ title: `请完整选择第${i + 1}个地址`, icon: 'none' });
        }
        // 只有非公安时才校验缴费方案
        if (!addr.isPolice && !addr.plan) {
          return uni.showToast({ title: `请选择第${i + 1}个地址的缴费方案`, icon: 'none' });
        }
        // 如果有运维费，需要校验年限选择
        if (addr.monthPrice && !addr.maintenanceDuration) {
          return uni.showToast({ title: `请选择第${i + 1}个地址的运维费年限`, icon: 'none' });
        }
      }
      this.isPaying = true;
      try {
        // 组装订单详情列表
        const orderDetailList = this.formData.addressList.map(addr => {
          // 使用新的计算逻辑：price(安装费+抓拍枪费) + 月租 * 年份
          let unitPrice = 0; // 运维费年费总价
          let installPrice = 0; // 安装费+抓拍枪费的总和
          
          if (!addr.isPolice) {
            if (addr.monthPrice && !isNaN(addr.monthPrice)) {
              const duration = addr.maintenanceDuration || 1;
              const monthlyRent = parseFloat(addr.monthPrice);
              unitPrice = monthlyRent * 12 * duration; // 运维费总额
              
              // 获取对应的方案price（安装费+拍杆费）
              const yearsStr = duration === 1 ? '1年' : '2年';
              const selectedInstallType = addr.selectedInstallType;
              // 优先使用接口返回的方案数据
              const planDataSource = addr.planOptionsFromApi && addr.planOptionsFromApi.length > 0 
                ? addr.planOptionsFromApi 
                : this.planOptions;
              const matchedPlan = planDataSource.find(plan => {
                const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
                const matchesRentAndYear = planMonthlyRent === monthlyRent && plan.years === yearsStr;
                
                // 如果有选中的安装类型，也要匹配
                if (selectedInstallType) {
                  return matchesRentAndYear && plan.installType === selectedInstallType;
                }
                
                return matchesRentAndYear;
              });
              installPrice = matchedPlan ? matchedPlan.price : 0;
            } else {
              const plan = this.planList.find(p => p.id == addr.plan) || {};
              unitPrice = plan.price || 0;
            }
          }
          // 公安类型只计算工程金额，不计算安装费和运维费
          
          const projectPrice = parseFloat(addr.engineeringFee) || 0;
          const totalPrice = unitPrice + installPrice + projectPrice;

          console.log('addr数据:', {
            province: addr.province,
            city: addr.city,
            district: addr.district,
            street: addr.street,
            village: addr.village
          });
          
          console.log('价格计算详情:', {
            isPolice: addr.isPolice,
            monthPrice: addr.monthPrice,
            maintenanceDuration: addr.maintenanceDuration,
            unitPrice: unitPrice, // 运维费年费总价
            installPrice: installPrice, // 安装费（公安类型为0）
            projectPrice: projectPrice, // 工程金额
            totalPrice: totalPrice,
            说明: addr.isPolice ? '公安类型-只计算工程金额' : '非公安-计算运维费+安装费+工程金额'
          });
          
          return {
            address: addr.fullAddress || '',
            buyCount: addr.isPolice ? 0 : ((addr.maintenanceDuration || 1) * 12), // 将年转换为月
            city: Number(addr.city) || 0,
            country: 0,
            deptId: Number(addr.street) || 0,
            district: Number(addr.district) || 0,
            door: addr.door || '',
            houseId: Number(addr.addressId) || 0,
            isPolice: addr.isPolice ? '1' : '0',
            name: this.formData.name,
            phone: this.formData.phone,
            province: Number(addr.province) || 0,
            street: Number(addr.street) || 0,
            unitPrice: unitPrice, // 运维费年费总价
            village: Number(addr.village) || 0,
            planId: addr.plan ? Number(addr.plan) : 0,
            projectPrice: projectPrice,
            installPrice: installPrice,
            // 传入查询到的installPrice字符串数组
            installPriceList: addr.installPriceList ? JSON.stringify(addr.installPriceList) : '[]',
            // 传入方案名称
            installPriceName: addr.selectedPlanData ? addr.selectedPlanData.name : '',
            maintenancePrice: unitPrice, // 专门的运维费字段
            totalPrice: totalPrice,
            type: 4
          };
        });

        
        // 组装后端要求的参数
        const orderParams = {
          chCardNo: '',
          chIdNo: '',
          chMobile: this.formData.phone,
          chName: this.formData.name,
          orderDetailList: orderDetailList,
          payChannel: '1',
          protocolNo: '',
          openid: uni.getStorageSync('wechat_openid'),
          remark: `${this.formData.addressList.map(addr => addr.fullAddress).join('；')}`,
          type: 4
        };
        const res = await addOrderInfo(orderParams);
        if (res.code === 200 && res.data) {
          res.data['door'] = this.formData.addressList[0].door;
          
          // 补充运维费和安装费信息到支付确认页面
          const totalMaintenancePrice = orderDetailList.reduce((sum, item) => sum + (item.unitPrice || 0), 0);
          const totalInstallPrice = orderDetailList.reduce((sum, item) => sum + (item.installPrice || 0), 0);
          const totalProjectPrice = orderDetailList.reduce((sum, item) => sum + (item.projectPrice || 0), 0);
          
          res.data['maintenancePrice'] = totalMaintenancePrice; // 运维费总计
          res.data['installPrice'] = totalInstallPrice; // 安装费总计
          res.data['projectPrice'] = totalProjectPrice; // 工程费总计
          res.data['correctTotalPrice'] = totalMaintenancePrice + totalInstallPrice + totalProjectPrice; // 正确的总价
          res.data['orderDetails'] = orderDetailList; // 完整的订单详情
          
          uni.navigateTo({
            url: `/pages/mine/maintenance/payConfirm?data=${encodeURIComponent(JSON.stringify(res.data))}`
          });
        } else {
          uni.showToast({ title: res.msg || '下单失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '下单失败', icon: 'none' });
      } finally {
        this.isPaying = false;
      }
    },
    async getLandlordList(searchKeyword = '') {
      this.landlordSearchLoading = true;
      try {
        // 使用正确的接口地址和参数，添加搜索关键词
        const params = {
          pageNum: 1,
          pageSize: 50, // 适当减少数量
          roleId: 100
        };

        // 如果有搜索关键词，添加到参数中
        if (searchKeyword && searchKeyword.trim()) {
          params.nickName = searchKeyword.trim(); // 先按姓名搜索
        }
        
        const res = await request({ 
          url: '/system/role/authUser/allocatedListNoDataScope', 
          method: 'get', 
          params 
        });
        
        console.log('房东接口返回数据:', res);
        if (res.code === 200 && res.rows && res.rows.length > 0) {
          this.filteredLandlords = res.rows;
          this.hasSearched = true;
          console.log('姓名搜索完成，关键词:', searchKeyword, '结果数量:', res.rows.length);
        } else {
          // 姓名搜索无结果，再按手机号搜索
          if (searchKeyword && searchKeyword.trim()) {
            params.phonenumber = searchKeyword.trim();
            delete params.nickName;
            
            const phoneRes = await request({
              url: '/system/role/authUser/allocatedListNoDataScope',
              method: 'get',
              params
            });
            
            if (phoneRes.code === 200 && phoneRes.rows && phoneRes.rows.length > 0) {
              this.filteredLandlords = phoneRes.rows;
              this.hasSearched = true;
              console.log('手机号搜索完成，关键词:', searchKeyword, '结果数量:', phoneRes.rows.length);
            } else {
              this.filteredLandlords = [];
              this.hasSearched = true;
              console.log('姓名和手机号均无搜索结果');
            }
          } else {
            this.filteredLandlords = [];
            this.hasSearched = true;
          }
        }
      } catch (e) {
        console.error('获取房东列表失败', e);
        this.filteredLandlords = [];
        this.hasSearched = true;
      } finally {
        this.landlordSearchLoading = false;
      }
    },
    filterLandlord(input, option) {
      if (!input) return true;
      // 支持姓名和手机号的任意部分模糊匹配
      const match = option.text.match(/^(.*)（(\d{11})）$/);
      if (match) {
        const name = match[1];
        const phone = match[2];
        return name.includes(input) || phone.includes(input);
      }
      return option.text.includes(input);
    },
    async onLandlordSelect(landlord) {
      console.log('选择房东:', landlord);
      this.landlordId = landlord.userId;
      this.formData.name = landlord.nickName || landlord.nickName;
      this.formData.phone = landlord.phonenumber;
      // 拉取房产信息
      await this.fetchHouseListAllByLandlord(landlord.userId);
    },
    async fetchHouseListAllByLandlord(landlordId) {
      try {
        const res = await request({
          url: '/door/house/list',
          method: 'get',
          params: { pageNum: 1, pageSize: 7000, landlordId }
        });
        if (res.code === 200 && res.rows) {
          this.houseList = res.rows;
          this.filteredHouseList = this.houseList;
          this.showHouseList = true;
        } else {
          this.houseList = [];
          this.filteredHouseList = [];
          this.showHouseList = true;
        }
      } catch (e) {
        this.houseList = [];
        this.filteredHouseList = [];
        this.showHouseList = true;
      }
    },
    getFullDeptNameByIds({ province, city, district, street, village }) {
      // 递归deptTree查找名称，顺序：省/市/区/镇/村
      let names = [];
      let node = this.deptTree && this.deptTree[0];
      if (!node) return '';
      function findChild(children, id) {
        if (!children || !id) return null;
        for (let c of children) {
          if (c.id === id) return c;
        }
        return null;
      }
      let cur = node;
      if (province && cur) { cur = findChild(cur.children, province); if (cur) names.push(cur.label); }
      if (city && cur) { cur = findChild(cur.children, city); if (cur) names.push(cur.label); }
      if (district && cur) { cur = findChild(cur.children, district); if (cur) names.push(cur.label); }
      if (street && cur) { cur = findChild(cur.children, street); if (cur) names.push(cur.label); }
      if (village && cur) { cur = findChild(cur.children, village); if (cur) names.push(cur.label); }
      return names.join('/')
    },
    onLandlordInput(e) {
      // 处理输入事件，e可能是事件对象或直接的值
      let input = '';
      if (typeof e === 'string') {
        input = e;
      } else if (e && e.detail && e.detail.value !== undefined) {
        input = e.detail.value;
      } else if (e && e.target && e.target.value !== undefined) {
        input = e.target.value;
      } else {
        input = e || '';
      }

      input = input.trim();
      console.log('房东搜索输入:', input);

      // 清除之前的定时器
      if (this.landlordSearchDebounceTimer) {
        clearTimeout(this.landlordSearchDebounceTimer);
      }

      // 如果输入为空，清空结果
      if (!input) {
        this.filteredLandlords = [];
        this.hasSearched = false;
        this.landlordSearchLoading = false;
        return;
      }

      // 设置防抖定时器
      this.landlordSearchDebounceTimer = setTimeout(() => {
        this.searchLandlordByKeyword(input);
      }, 300); // 300ms 防抖
    },

    // 新增：根据关键词搜索房东
    async searchLandlordByKeyword(keyword) {
      if (!keyword || keyword.length < 1) {
        this.filteredLandlords = [];
        this.hasSearched = false;
        return;
      }

      console.log('开始搜索房东，关键词:', keyword);
      await this.getLandlordList(keyword);
    },
    onPoliceSwitch(e, idx) {
      this.formData.addressList[idx].isPolice = e.detail.value;
      // 切换为公安时清空套餐选择
      if (e.detail.value) {
        this.formData.addressList[idx].plan = '';
      }
    },

    // 房产搜索框获得焦点
    onHouseSearchFocus() {
      // 可以在这里添加搜索框获得焦点时的逻辑
    },

    // 房产搜索框失去焦点
    onHouseSearchBlur() {
      // 可以在这里添加搜索框失去焦点时的逻辑
    },

    // 清空房产搜索
    clearHouseSearch() {
      this.houseSearchKeyword = '';
      this.filteredHouseList = this.houseList;
      console.log('清空搜索，显示全部房产:', this.houseList.length, '条');
    },

    // 拨打客服电话
    callService() {
      uni.showModal({
        title: '拨打客服电话',
        content: '确定拨打客服电话 4006983338 吗？',
        success: (res) => {
          if (res.confirm) {
            uni.makePhoneCall({
              phoneNumber: '4006983338',
              success: () => {
                console.log('拨打客服电话成功');
              },
              fail: (err) => {
                console.error('拨打客服电话失败:', err);
                uni.showToast({
                  title: '拨打失败，请手动拨打',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    },
    maskPhone(phone) {
      // console.log('phone', (phone.substr(0,3) + '****' + phone.substr(7)));
      if (!phone || phone.length < 7) return phone;
      this.jiamiphone = phone.substr(0, 3) + '****' + phone.substr(7);
      return phone.substr(0, 3) + '****' + phone.substr(7);
    },
    maskName(name) {
      if (!name) return '';
      if (name.length === 2) return name[0] + '*';
      if (name.length > 2) return name[0] + '*'.repeat(name.length - 2) + name[name.length - 1];
      return name;
    },
    // 移除原有的getPlanList方法，改为使用配置数据
    initPlanList() {
      // 使用配置的方案数据，不再调用接口
      this.planList = [
        { id: 1, name: '智能门禁方案', tag1: '', tag2: '', desc1: '基础功能', desc2: '按需配置', num: 1, price: 0 }
      ];
      console.log('初始化方案列表完成');
    },
    
    // 获取地址相关的价格信息（安装费、运维费等）
    async fetchAddressPrice(deptId) {
      try {
        const res = await request({
          url: `/admin-api/door/dept/price/${deptId}`,
          method: 'get'
        });
        if (res.code === 200 && res.data) {
          // 解析安装费字符串数组
          let installPriceList = [];
          if (res.data.installPrice && typeof res.data.installPrice === 'string') {
            try {
              installPriceList = JSON.parse(res.data.installPrice);
            } catch (e) {
              console.error('解析安装费数据失败:', e);
              installPriceList = [];
            }
          }
          
          return {
            ...res.data,
            installPriceList: installPriceList // 解析后的安装费数组
          };
        } else {
          console.log('获取地址价格失败:', res.msg);
          return null;
        }
      } catch (e) {
        console.error('获取地址价格异常:', e);
        return null;
      }
    },
    
    // 根据年限获取安装费
    getInstallPriceByYears(installPriceList, years) {
      // 处理字符串格式的installPriceList
      let priceList = installPriceList;
      if (typeof installPriceList === 'string') {
        try {
          priceList = JSON.parse(installPriceList);
        } catch (error) {
          console.error('解析installPriceList失败:', error);
          return 0;
        }
      }
      
      if (!priceList || !Array.isArray(priceList)) {
        return 0;
      }
      
      // 处理年份匹配：数字转字符串
      const yearsStr = years === 1 ? '1年' : years === 2 ? '2年' : years;
      const found = priceList.find(item => item.years === yearsStr);
      return found ? (found.price || 0) : 0;
    },
    
    // 计算方案价格（运维费 + 安装费）
    calculatePlanPrice(item) {
      if (!item.monthPrice) {
        return '0.00';
      }
      
      const duration = item.maintenanceDuration || 1;
      const monthlyPrice = parseFloat(item.monthPrice) || 0;
      const maintenanceTotal = monthlyPrice * 12 * duration; // 运维费总额
      
      // 获取安装费
      const installPrice = this.getCurrentInstallPrice(item);
      
      const totalPrice = maintenanceTotal + installPrice;
      return totalPrice.toFixed(2);
    },
    
    // 计算方案总价（运维费 + 安装费）
    calculatePlanTotalPrice(item) {
      if (!item.monthPrice) {
        return '0.00';
      }
      
      const duration = item.maintenanceDuration || 1;
      const monthlyPrice = parseFloat(item.monthPrice) || 0;
      const maintenancePrice = monthlyPrice * 12 * duration; // 运维费总额
      
      // 获取当前年限对应的安装费
      const installPrice = this.getCurrentInstallPrice(item);
      
      const totalPrice = maintenancePrice + installPrice;
      return totalPrice.toFixed(2);
    },
    
    // 获取当前年限对应的安装费
    getCurrentInstallPrice(item) {
      const duration = item.maintenanceDuration || 1;
      const monthlyRent = parseFloat(item.monthPrice) || 0;
      const selectedInstallType = item.selectedInstallType;
      
      // 优先使用接口返回的方案数据
      const planDataSource = item.planOptionsFromApi && item.planOptionsFromApi.length > 0 
        ? item.planOptionsFromApi 
        : this.planOptions;
      
      // 如果有方案数据，使用精确匹配
      if (planDataSource && planDataSource.length > 0) {
        const yearsStr = duration === 1 ? '1年' : '2年';
        const matchedPlan = planDataSource.find(plan => {
          const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
          const matchesRentAndYear = planMonthlyRent === monthlyRent && plan.years === yearsStr;
          
          // 如果有选中的安装类型，也要匹配
          if (selectedInstallType) {
            return matchesRentAndYear && plan.installType === selectedInstallType;
          }
          
          return matchesRentAndYear;
        });
        
        return matchedPlan ? (matchedPlan.price || 0) : 0;
      }
      
      // 如果没有方案数据，尝试使用installPriceList
      if (item.installPriceList) {
        return this.getInstallPriceByYears(item.installPriceList, duration);
      }
      
      return 0;
    },
    
    // 解析接口返回的installPrice数据
    parseInstallPriceData(installPriceStr) {
      try {
        if (typeof installPriceStr === 'string') {
          return JSON.parse(installPriceStr);
        } else if (Array.isArray(installPriceStr)) {
          return installPriceStr;
        }
        return [];
      } catch (e) {
        console.error('解析installPrice数据失败:', e);
        return [];
      }
    },
    
    // 根据运维费更新可用方案
    updateAvailablePlans(addressIndex) {
      const addressItem = this.formData.addressList[addressIndex];
      if (!addressItem.monthPrice) {
        this.filteredPlanOptions = [];
        this.availableYears = [];
        return;
      }
      
      // 优先使用接口返回的方案数据，如果没有则使用默认配置
      const planDataSource = addressItem.planOptionsFromApi && addressItem.planOptionsFromApi.length > 0 
        ? addressItem.planOptionsFromApi 
        : this.planOptions;
      
      // 根据月租过滤方案
      const monthlyRent = parseFloat(addressItem.monthPrice) || 0;
      console.log('开始匹配方案 - 当前运维费:', monthlyRent, '元/月');
      console.log('可用方案数据:', planDataSource);
      
      this.filteredPlanOptions = planDataSource.filter(plan => {
        const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
        console.log('比较方案:', plan.name, '月租:', planMonthlyRent, '是否匹配:', planMonthlyRent === monthlyRent);
        return planMonthlyRent === monthlyRent;
      });
      
      console.log('过滤后的方案:', this.filteredPlanOptions);
      
      // 提取可用年份
      const years = [...new Set(this.filteredPlanOptions.map(plan => {
        return plan.years === '1年' ? 1 : 2; // 转换为数字
      }))];
      
      this.availableYears = years.map(year => ({
        years: year,
        label: year === 1 ? '一年' : '两年'
      }));
      
      console.log('可用年份:', this.availableYears);
      
      // 获取新的年份选项结构
      const yearOptions = this.getAvailableYearsForAddress(addressIndex);
      
      // 默认选择第一个年份选项
      if (yearOptions.length > 0) {
        const firstOption = yearOptions[0];
        addressItem.maintenanceDuration = firstOption.years;
        
        // 如果有安装类型，保存它
        if (firstOption.installType) {
          addressItem.selectedInstallType = firstOption.installType;
          addressItem.selectedPlanData = firstOption.planData;
        }
        
        this.updatePlanPriceWithType(addressIndex, firstOption);
        console.log('地址选择完成 - 运维费:', monthlyRent, '元/月，可用方案:', this.filteredPlanOptions.length, '个，可用年份:', yearOptions.map(y => y.label).join(','));
      } else {
        console.warn('没有找到匹配的方案，运维费:', monthlyRent, '元/月');
      }
    },
    
    // 更新方案价格
    updatePlanPrice(addressIndex, selectedYears) {
      const addressItem = this.formData.addressList[addressIndex];
      const monthlyRent = parseFloat(addressItem.monthPrice) || 0;
      
      // 优先使用接口返回的方案数据
      const planDataSource = addressItem.planOptionsFromApi && addressItem.planOptionsFromApi.length > 0 
        ? addressItem.planOptionsFromApi 
        : this.planOptions;
      
      // 找到匹配的方案
      const yearsStr = selectedYears === 1 ? '1年' : '2年';
      const matchedPlan = planDataSource.find(plan => {
        const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
        return planMonthlyRent === monthlyRent && plan.years === yearsStr;
      });
      
      console.log('更新方案价格 - 运维费:', monthlyRent, '年份:', selectedYears, '匹配的方案:', matchedPlan);
      
      if (matchedPlan) {
        this.currentSelectedPlan = matchedPlan;
        // 设置安装费（installFee + poleFee）
        const totalInstallPrice = (matchedPlan.installFee || 0) + (matchedPlan.poleFee || 0);
        this.$set(addressItem, 'installPrice', totalInstallPrice);
        console.log(`选择${selectedYears}年方案：${matchedPlan.name}，安装费：${totalInstallPrice}元`);
      } else {
        console.warn('未找到匹配的方案 - 运维费:', monthlyRent, '年份:', selectedYears);
      }
    },
    
    // 获取地址可用年份
    getAvailableYearsForAddress(addressIndex) {
      const addressItem = this.formData.addressList[addressIndex];
      if (!addressItem.monthPrice) {
        return this.durationOptions;
      }
      
      // 优先使用接口返回的方案数据
      const planDataSource = addressItem.planOptionsFromApi && addressItem.planOptionsFromApi.length > 0 
        ? addressItem.planOptionsFromApi 
        : this.planOptions;
      
      const monthlyRent = parseFloat(addressItem.monthPrice) || 0;
      const availablePlans = planDataSource.filter(plan => {
        const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
        return planMonthlyRent === monthlyRent;
      });
      
      // 按年份分组方案
      const yearGroups = {};
      availablePlans.forEach(plan => {
        const yearNum = plan.years === '1年' ? 1 : 2;
        if (!yearGroups[yearNum]) {
          yearGroups[yearNum] = [];
        }
        yearGroups[yearNum].push(plan);
      });
      
      // 生成年份选项，如果有多个相同年份，根据installType区分
      const yearOptions = [];
      Object.keys(yearGroups).forEach(year => {
        const yearNum = parseInt(year);
        const plans = yearGroups[yearNum];
        
        if (plans.length === 1) {
          // 只有一个方案，直接显示
          yearOptions.push({
            years: yearNum,
            label: yearNum === 1 ? '一年' : '两年',
            installType: plans[0].installType,
            planData: plans[0]
          });
        } else {
          // 有多个相同年份的方案，按installType区分
          plans.forEach(plan => {
            const baseLabel = yearNum === 1 ? '一年' : '两年';
            const typeLabel = plan.installType === '新装' ? '新装' : '升级';
            yearOptions.push({
              years: yearNum,
              label: `${baseLabel}(${typeLabel})`,
              installType: plan.installType,
              planData: plan
            });
          });
        }
      });
      
      return yearOptions;
    },
    
    // 判断年份选项是否被选中
    isYearOptionSelected(item, option) {
      // 如果没有installType信息，使用原有逻辑
      if (!option.installType) {
        return item.maintenanceDuration === option.years;
      }
      
      // 有installType信息时，需要同时匹配年份和安装类型
      return item.maintenanceDuration === option.years && 
             item.selectedInstallType === option.installType;
    },
    
    // 新的年份选择方法，支持安装类型
    selectMaintenanceDurationWithType(idx, option) {
      this.$set(this.formData.addressList[idx], 'maintenanceDuration', option.years);
      
      // 如果有安装类型，保存它
      if (option.installType) {
        this.$set(this.formData.addressList[idx], 'selectedInstallType', option.installType);
        this.$set(this.formData.addressList[idx], 'selectedPlanData', option.planData);
      }
      
      // 使用新的方案匹配逻辑
      this.updatePlanPriceWithType(idx, option);
      
      // 强制更新视图以重新计算所有方案的价格显示
      this.$forceUpdate();
    },
    
    // 支持安装类型的价格更新方法
    updatePlanPriceWithType(addressIndex, option) {
      const addressItem = this.formData.addressList[addressIndex];
      
      // 如果有具体的方案数据，直接使用
      if (option.planData) {
        this.currentSelectedPlan = option.planData;
        const installFee = option.planData.installFee || 0;
        const poleFee = option.planData.poleFee || 0;
        const totalInstallPrice = option.planData.price || 0;
        this.$set(addressItem, 'installPrice', totalInstallPrice);
        
        let feeDetails = [];
        if (installFee > 0) feeDetails.push(`安装费${installFee}元`);
        if (poleFee > 0) feeDetails.push(`抓拍枪费${poleFee}元`);
        const feeText = feeDetails.length > 0 ? `（${feeDetails.join(' + ')}）` : '';
        
        console.log(`选择${option.years}年(${option.installType})方案：${option.planData.name}，总费用：${totalInstallPrice}元${feeText}`);
        return;
      }
      
      // 如果没有具体方案数据，使用原有逻辑
      this.updatePlanPrice(addressIndex, option.years);
    },
    
    // 获取费用明细文本
    getFeeBreakdownText(planInfo) {
      if (!planInfo) return '';
      
      let feeDetails = [];
      if (planInfo.installFee > 0) {
        feeDetails.push(`安装费¥${planInfo.installFee.toFixed(2)}`);
      }
      if (planInfo.poleFee > 0) {
        feeDetails.push(`抓拍枪费¥${planInfo.poleFee.toFixed(2)}`);
      }
      
      return feeDetails.length > 0 ? feeDetails.join(' + ') : '无其他费用';
    },
    
    // 获取新的安装费
    getNewInstallPrice(item, addressIndex) {
      if (!item.monthPrice) return 0;
      
      const addressItem = this.formData.addressList[addressIndex];
      
      // 如果有选中的具体方案数据，直接使用
      if (addressItem && addressItem.selectedPlanData) {
        return addressItem.selectedPlanData.price || 0;
      }
      
      const planDataSource = addressItem && addressItem.planOptionsFromApi && addressItem.planOptionsFromApi.length > 0 
        ? addressItem.planOptionsFromApi 
        : this.planOptions;
      
      const duration = item.maintenanceDuration || 1;
      const monthlyRent = parseFloat(item.monthPrice) || 0;
      const yearsStr = duration === 1 ? '1年' : '2年';
      const selectedInstallType = addressItem ? addressItem.selectedInstallType : null;
      
      const matchedPlan = planDataSource.find(plan => {
        const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
        const matchesRentAndYear = planMonthlyRent === monthlyRent && plan.years === yearsStr;
        
        // 如果有选中的安装类型，也要匹配
        if (selectedInstallType) {
          return matchesRentAndYear && plan.installType === selectedInstallType;
        }
        
        return matchesRentAndYear;
      });
      
      return matchedPlan ? matchedPlan.price : 0;
    },
    
    // 获取当前方案信息
    getCurrentPlanInfo(item, addressIndex) {
      if (!item.monthPrice) return null;
      
      const addressItem = this.formData.addressList[addressIndex];
      
      // 如果有选中的具体方案数据，直接返回
      if (addressItem && addressItem.selectedPlanData) {
        return addressItem.selectedPlanData;
      }
      
      const planDataSource = addressItem && addressItem.planOptionsFromApi && addressItem.planOptionsFromApi.length > 0 
        ? addressItem.planOptionsFromApi 
        : this.planOptions;
      
      const duration = item.maintenanceDuration || 1;
      const monthlyRent = parseFloat(item.monthPrice) || 0;
      const yearsStr = duration === 1 ? '1年' : '2年';
      const selectedInstallType = addressItem ? addressItem.selectedInstallType : null;
      
      return planDataSource.find(plan => {
        const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
        const matchesRentAndYear = planMonthlyRent === monthlyRent && plan.years === yearsStr;
        
        // 如果有选中的安装类型，也要匹配
        if (selectedInstallType) {
          return matchesRentAndYear && plan.installType === selectedInstallType;
        }
        
        return matchesRentAndYear;
      });
    },
    
    // 新的总价计算方法
    calculateNewPlanTotalPrice(item, addressIndex) {
      if (!item.monthPrice) {
        return '0.00';
      }
      
      const addressItem = this.formData.addressList[addressIndex];
      const planDataSource = addressItem && addressItem.planOptionsFromApi && addressItem.planOptionsFromApi.length > 0 
        ? addressItem.planOptionsFromApi 
        : this.planOptions;
      
      const duration = item.maintenanceDuration || 1;
      const monthlyRent = parseFloat(item.monthPrice) || 0;
      const selectedInstallType = item.selectedInstallType;
      const maintenanceTotal = monthlyRent * 12 * duration; // 运维费总额
      
      // 获取对应的方案price（安装费+拍杆费）
      const yearsStr = duration === 1 ? '1年' : '2年';
      const matchedPlan = planDataSource.find(plan => {
        const planMonthlyRent = parseFloat(plan.monthlyRent) || 0;
        const matchesRentAndYear = planMonthlyRent === monthlyRent && plan.years === yearsStr;
        
        // 如果有选中的安装类型，也要匹配
        if (selectedInstallType) {
          return matchesRentAndYear && plan.installType === selectedInstallType;
        }
        
        return matchesRentAndYear;
      });
      
      const installPrice = matchedPlan ? matchedPlan.price : 0;
      
      console.log('calculateNewPlanTotalPrice - 月租:', monthlyRent, '年份:', duration, '安装类型:', selectedInstallType, '匹配方案:', matchedPlan, '运维费:', maintenanceTotal, '安装费:', installPrice);
      
      const totalPrice = maintenanceTotal + installPrice;
      return totalPrice.toFixed(2);
    }
  },
  mounted() {
    this.getDeptTree();
    this.initPlanList();
    
    // 测试方案匹配逻辑
    console.log('初始化方案配置:', this.planOptions);
    
    // 自动读取上次缓存
    const cache = uni.getStorageSync('paymentFormData');
    if (cache) {
      try {
        const parsed = typeof cache === 'string' ? JSON.parse(cache) : cache;
        if (parsed && parsed.name) {
          this.formData.name = parsed.name;
          this.formData.phone = parsed.phone;
          this.formData.addressList = parsed.addressList || [{
            province: '', city: '', district: '', street: '', village: '', addressId: '', fullAddress: '', noAddress: false,
            plan: '',
            engineeringFee: '',
            isPolice: false,
            monthPrice: 0,
            installPrice: 0,
            cardPrice: 0,
            giftMonthOfByOneYear: 0,
            maintenanceDuration: 1,
            installPriceList: []
          }];
        }
      } catch (e) { }
    }
  },
  watch: {
    formData: {
      handler(val) {
        uni.setStorageSync('paymentFormData', JSON.stringify(val));
      },
      deep: true
    }
  }
}
</script>

<style lang="scss" scoped>
$primary: #1989fa;
$danger: #f56c6c;
$card-radius: 24rpx;
$input-radius: 16rpx;
$shadow: 0 2rpx 8rpx rgba(25, 137, 250, 0.06);
$border: 1px solid #f0f0f0;
$placeholder: #bbb;

.payment-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 0 0 120rpx 0;
}

.info-section {
  background-color: #fff;
  border-radius: $card-radius;
  margin: 20rpx 20rpx 0 20rpx;
  box-shadow: $shadow;
  padding: 0 30rpx;
}

.section-title {
  display: flex;
  align-items: center;
  padding: 24rpx 0 16rpx;

  .section-title-text {
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
  }

  .required {
    color: $danger;
    margin-left: 10rpx;
    font-size: 28rpx;
  }

  .close-icon {
    font-size: 36rpx;
    color: #999;
    margin-left: auto;
    cursor: pointer;
    padding: 8rpx;
  }
}

.input-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #f2f2f2;

  .required {
    color: $danger;
    margin-right: 6rpx;
    font-size: 26rpx;
  }

  .label {
    width: 160rpx;
    font-size: 28rpx;
    color: #333;
  }

  .input {
    flex: 1;
    font-size: 28rpx;
    color: #222;
    background: #f7f7f7;
    border-radius: $input-radius;
    padding: 16rpx 24rpx;
    border: none;
    min-height: 64rpx;
  }

  &.arrow-item {
    .right-content {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .placeholder {
        color: #bbb;
      }

      .arrow {
        font-size: 32rpx;
        color: #bbb;
        margin-left: 10rpx;
      }
    }
  }
}

.plan-section,
.other-fee-section {
  background: none;
  border-radius: 0;
  margin: 0;
  box-shadow: none;
  padding: 0;
  border-top: 1px solid #f0f0f0;
}

.plan-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 24rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.plan-item {
  width: 100%;
  min-height: 88rpx;
  background: #fff;
  border-radius: 24rpx;
  border: 2rpx solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  font-size: 30rpx;
  padding: 28rpx 32rpx 28rpx 32rpx;
  box-sizing: border-box;
  margin-bottom: 0;
  transition: border 0.2s, background 0.2s;
  word-break: break-all;
  white-space: normal;

  .plan-checkbox {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    border: 2rpx solid #ddd;
    margin-right: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: border-color 0.2s;

    .checkbox-inner {
      width: 26rpx;
      height: 26rpx;
      border-radius: 50%;
      background-color: $primary;
    }
  }

  .plan-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    min-width: 0; // 防止内容溢出

    .plan-name {
      font-size: 32rpx;
      color: #222;
      font-weight: 600;
      margin-bottom: 6rpx;
      display: flex;
      align-items: center;
      flex-wrap: wrap; // 允许换行
      width: 100%; // 占满宽度

      .plan-tag {
        font-size: 26rpx;
        color: #bbb;
        margin-left: 8rpx;
        font-weight: normal;

        &.plan-tag-highlight {
          color: #ff7a45;
          font-weight: 600;
        }
      }

      .recommend-tag {
        background-color: #ff7a45;
        color: #fff;
        font-size: 22rpx;
        width: 38rpx;
        height: 38rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: normal;
        margin-left: 10rpx;
      }
    }

    .plan-desc {
      font-size: 26rpx;
      color: #888;
      line-height: 1.6;
      margin-bottom: 2rpx;
      
      &.plan-gift {
        color: #ff7a45;
        font-weight: 600;
      }
    }
  }

  // 智能方案卡片样式
  .smart-plan-card {
    background: linear-gradient(135deg, #f8fbff 0%, #f0f8ff 100%);
    border: 2rpx solid #1989fa;
    border-radius: 20rpx;
    padding: 0;
    box-shadow: 0 8rpx 24rpx rgba(25, 137, 250, 0.15);
    overflow: hidden;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2rpx);
      box-shadow: 0 12rpx 32rpx rgba(25, 137, 250, 0.2);
    }

    .plan-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 24rpx 28rpx;
      background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
      border-bottom: 1rpx solid #e8f4ff;

      .plan-checkbox-wrapper {
        margin-right: 20rpx;

        .plan-checkbox.selected {
          width: 44rpx;
          height: 44rpx;
          border-radius: 50%;
          background: linear-gradient(135deg, #1989fa 0%, #0d7fe8 100%);
          border: none;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.3);

          .checkbox-inner {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;

            .check-icon {
              color: #ffffff;
              font-size: 24rpx;
              font-weight: bold;
            }
          }
        }
      }

      .plan-title-section {
        flex: 1;

        .plan-name-row {
          display: flex;
          align-items: center;
          flex-wrap: wrap;

          .plan-name {
            font-size: 34rpx;
            font-weight: 600;
            color: #1a1a1a;
            margin-right: 16rpx;
          }

          .plan-badges {
            display: flex;
            align-items: center;
            gap: 8rpx;

            .plan-tag.featured {
              background: linear-gradient(135deg, #ff6b35 0%, #ff8f00 100%);
              color: #ffffff;
              font-size: 22rpx;
              padding: 4rpx 12rpx;
              border-radius: 12rpx;
              font-weight: 500;
              box-shadow: 0 2rpx 8rpx rgba(255, 107, 53, 0.25);
            }

            .recommend-badge {
              background: linear-gradient(135deg, #ff4757 0%, #ff3838 100%);
              color: #ffffff;
              font-size: 20rpx;
              width: 36rpx;
              height: 36rpx;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: 600;
              box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.3);
            }
          }
        }
      }

      .plan-price-section {
        .price-display {
          display: flex;
          align-items: baseline;
          flex-direction: column;
          align-items: flex-end;

          .price-amount {
            font-size: 42rpx;
            font-weight: 700;
            color: #1989fa;
            line-height: 1;
          }

          .price-unit {
            font-size: 24rpx;
            color: #666;
            margin-top: 2rpx;
          }
        }
      }
    }

    .plan-details {
      padding: 20rpx 28rpx 28rpx 28rpx;
      background: #ffffff;

      .detail-item {
        display: flex;
        align-items: center;
        padding: 12rpx 0;
        border-bottom: 1rpx solid #f5f7fa;

        &:last-child {
          border-bottom: none;
          padding-bottom: 0;
        }

        .detail-icon {
          font-size: 32rpx;
          margin-right: 16rpx;
          width: 44rpx;
          height: 44rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        }

        .detail-text {
          font-size: 28rpx;
          color: #333;
          flex: 1;

          &.gift-text {
            background: linear-gradient(135deg, #ff6b35 0%, #ff8f00 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            font-weight: 600;
          }
        }

        &.maintenance .detail-icon {
          background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
        }

        &.install .detail-icon {
          background: linear-gradient(135deg, #fff3e0 0%, #ffcc02 100%);
        }

        &.gift .detail-icon {
          background: linear-gradient(135deg, #fce4ec 0%, #f8bbd9 100%);
        }

        &.maintenance-select {
          flex-direction: column;
          align-items: flex-start;
          padding: 16rpx 0 20rpx 0;

          .maintenance-options {
            flex: 1;
            width: 100%;

            .detail-label {
              font-size: 28rpx;
              color: #333;
              margin-bottom: 16rpx;
              display: block;
            }

            .duration-options {
              display: flex;
              gap: 12rpx;
              width: 100%;
              flex-wrap: wrap;

              .duration-option {
                flex: 1;
                min-width: 0;
                border: 2rpx solid #e0e0e0;
                border-radius: 16rpx;
                padding: 16rpx 12rpx;
                background: #fafafa;
                display: flex;
                flex-direction: column;
                align-items: center;
                cursor: pointer;
                transition: all 0.3s ease;

                &.active {
                  border-color: #1989fa;
                  background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%);
                  box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.15);

                  .option-radio {
                    border-color: #1989fa;
                    background: #1989fa;

                    .radio-inner {
                      background: #ffffff;
                      width: 12rpx;
                      height: 12rpx;
                      border-radius: 50%;
                    }
                  }

                  .option-title {
                    color: #1989fa;
                    font-weight: 600;
                  }

                  .option-price {
                    color: #1989fa;
                  }
                }

                .option-radio {
                  width: 32rpx;
                  height: 32rpx;
                  border: 2rpx solid #ddd;
                  border-radius: 50%;
                  margin-bottom: 8rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-shrink: 0;
                  transition: all 0.2s ease;
                }

                .option-content {
                  flex: 1;
                  display: flex;
                  flex-direction: column;

                  .option-title {
                    font-size: 26rpx;
                    color: #333;
                    font-weight: 500;
                    margin-bottom: 6rpx;
                    text-align: center;
                    width: 100%;
                  }

                  .option-price {
                    font-size: 28rpx;
                    color: #ff6b35;
                    font-weight: 600;
                    margin-bottom: 4rpx;
                    text-align: center;
                    width: 100%;
                  }

                  .option-gift {
                    font-size: 20rpx;
                    color: #ff8f00;
                    background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
                    padding: 2rpx 6rpx;
                    border-radius: 6rpx;
                    align-self: center;
                    font-weight: 500;
                    text-align: center;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  // 已移除冲突的duration-section样式

  // 简化版方案卡片
  .simple-plan-card {
    background: #ffffff;
    border: 2rpx solid #1989fa;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.1);

    .plan-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .plan-checkbox {
        width: 32rpx;
        height: 32rpx;
        background: #1989fa;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16rpx;

        .check-icon {
          color: #ffffff;
          font-size: 20rpx;
          font-weight: bold;
        }
      }

      .plan-name {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .plan-details {
      .detail-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12rpx 0;
        border-bottom: 1rpx solid #f5f5f5;

        &:last-child {
          border-bottom: none;
          padding-bottom: 0;
        }

        .detail-label {
          font-size: 26rpx;
          color: #666;
        }

        .detail-value {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }
  }

  .install-fee-section {
    background: #ffffff;
    margin: 16rpx 20rpx;
    padding: 0;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

    .section-header {
      padding: 24rpx 30rpx 16rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;

      .section-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .fee-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 24rpx 30rpx;

      .fee-left {
        flex: 1;

        .fee-name {
          font-size: 30rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 4rpx;
          display: block;
        }

        .fee-desc {
          font-size: 24rpx;
          color: #666;
          display: block;
        }
      }

      .fee-right {
        .fee-price {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
        }
      }
    }
  }

  .plan-price {
    font-size: 40rpx;
    color: #333;
    font-weight: bold;
    margin-left: 18rpx;
  }

  &.active {
    background: #eaf3ff;
    border: 2rpx solid $primary;

    .plan-price {
      color: $danger;
    }
  }
}

.add-address-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx 0;
  color: #007AFF;
  margin: 16rpx 0;
  background-color: #fff;

  .add-icon {
    font-size: 32rpx;
    margin-right: 8rpx;
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  height: 110rpx;
  z-index: 10;

  .total-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;

    .total-label {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 6rpx;
    }

    .total-amount-row {
      display: flex;
      align-items: flex-end;
    }

    .total-price {
      font-size: 40rpx;
      color: $danger;
      font-weight: bold;
      margin-right: 6rpx;
    }

    .total-unit {
      font-size: 28rpx;
      color: $danger;
      font-weight: bold;
    }
  }

  .confirm-btn {
    background-color: $primary;
    color: #fff;
    padding: 0 56rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 600;
    height: 80rpx;
    line-height: 80rpx;
    margin-left: 24rpx;
    box-shadow: 0 2rpx 8rpx rgba(25, 137, 250, 0.08);
    display: flex;
    align-items: center;
    justify-content: center;

    &.loading {
      background: #b2e5c8;
      color: #fff;
    }
  }
}

.no-address-tip {
  color: $danger;
  font-size: 28rpx;
  margin: 14rpx 0 0 36rpx;

  .phone {
    color: $primary;
  }
}

.address-divider {
  height: 18px;
  background: #f5f7fa;
  margin: 0 -24rpx 0 -24rpx;
  border-top: 1px solid #e5e5e5;
}

// 其它弹窗、下拉、面包屑等样式可按需继续细化...</style>

<style lang="scss">
.wx-popup-content {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 0 0 24rpx 0;
  min-height: 60vh;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.08);
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
}

.wx-popup-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;

  .wx-tab {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    padding: 28rpx 0 18rpx 0;
    color: #888;
    position: relative;
    cursor: pointer;

    &.active {
      color: #07c160;
      font-weight: bold;
      border-bottom: 4rpx solid #07c160;
      background: #f7f7f7;
    }
  }
}

.wx-popup-header {
  display: flex;
  align-items: center;
  padding: 18rpx 24rpx 0 24rpx;

  .wx-back-btn {
    margin-right: 12rpx;
    color: #07c160;
    font-size: 36rpx;
    cursor: pointer;
  }

  .wx-breadcrumb {
    display: flex;
    flex-wrap: wrap;

    .wx-breadcrumb-item {
      color: #07c160;
      font-size: 28rpx;
      margin-right: 8rpx;
      cursor: pointer;

      &:after {
        content: "/";
        color: #bbb;
        margin-left: 8rpx;
      }

      &:last-child:after {
        content: "";
      }
    }
  }
}

.wx-popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #222;
  padding: 24rpx 24rpx 12rpx 24rpx;
}

.wx-popup-title-sub {
  font-size: 28rpx;
  color: #07c160;
  padding: 12rpx 24rpx 0 24rpx;

  &.wx-blue-bar {
    border-left: 8rpx solid #07c160;
    padding-left: 16rpx;
    background: #f7f7f7;
  }
}

.wx-list-wrap {
  padding: 0 24rpx;

  .wx-list-item {
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 16rpx;
    padding: 28rpx 24rpx;
    font-size: 30rpx;
    color: #222;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    border: 1px solid #f0f0f0;
    transition: background 0.2s, border 0.2s;

    &.active,
    &:hover {
      background: #eafaf1;
      border: 1px solid #07c160;
      color: #07c160;
    }

    &.wx-list-item-blue {
      color: #1989fa;
      border-color: #1989fa;
      background: #f0faff;
    }

    .wx-arrow {
      font-size: 32rpx;
      color: #bbb;
      margin-left: 10rpx;
    }

    .wx-address-text {
      font-size: 28rpx;
      color: #333;
      word-break: break-all;
    }
  }
}

.wx-landlord-switch {
  padding: 18rpx 24rpx 0 24rpx;
}

.no-address-tip {
  background: linear-gradient(135deg, #fff5f5 0%, #fff0f0 100%);
  border: 1px solid #ffebeb;
  border-radius: 12rpx;
  padding: 24rpx;
  margin: 16rpx 24rpx;
  text-align: center;

  .no-address-content {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 12rpx;

    .no-address-text {
      color: #ff6b6b;
      font-size: 28rpx;
      font-weight: 500;
      margin-left: 8rpx;
    }
  }

  .contact-info {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;

    .contact-label {
      color: #666;
      font-size: 26rpx;
      margin-right: 8rpx;
    }

    .phone-number {
      color: #1989fa;
      font-size: 28rpx;
      font-weight: bold;
      text-decoration: underline;
      padding: 4rpx 8rpx;
      border-radius: 6rpx;
      background-color: rgba(25, 137, 250, 0.1);

      &:active {
        background-color: rgba(25, 137, 250, 0.2);
      }
    }
  }
}

// 添加搜索提示样式
.wx-search-tip {
  font-size: 26rpx;
  color: #666;
  padding: 16rpx 32rpx;
  text-align: center;
  background-color: #f7f7f7;
  margin-bottom: 12rpx;
  border-radius: 8rpx;
}

/* 添加搜索输入框样式 */
.wx-search-input {
  padding: 0 32rpx 16rpx 32rpx;

  .search-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    border: 1px solid #e9ecef;
    border-radius: 24rpx;
    padding: 20rpx 24rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;

    &:focus-within {
      border-color: #07c160;
      box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.15);
      background: linear-gradient(135deg, #f0fff4 0%, #ffffff 100%);
    }

    .house-search-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      background: transparent;
      border: none;
      outline: none;
      margin-left: 16rpx;
      line-height: 1.4;

      &::placeholder {
        color: #999;
        font-size: 26rpx;
      }

      &:focus {
        color: #07c160;
      }
    }

    .clear-btn {
      width: 36rpx;
      height: 36rpx;
      background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 22rpx;
      font-weight: bold;
      margin-left: 16rpx;
      cursor: pointer;
      transition: all 0.2s ease;
      box-shadow: 0 2rpx 6rpx rgba(255, 107, 107, 0.3);

      &:active {
        transform: scale(0.9);
        box-shadow: 0 1rpx 4rpx rgba(255, 107, 107, 0.4);
      }

      &:hover {
        background: linear-gradient(135deg, #ff5252 0%, #ff4444 100%);
        box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.4);
      }
    }
  }

  // 新的费用详情样式覆盖
  .smart-plan-card .plan-details {
    .detail-row {
      display: flex;
      gap: 20rpx;
      margin-bottom: 16rpx;

      .detail-item {
        flex: 1;
        background: rgba(255, 255, 255, 0.8);
        padding: 16rpx 20rpx;
        border-radius: 12rpx;
        border: 1rpx solid rgba(25, 137, 250, 0.15);
        display: block;

        .detail-label {
          font-size: 24rpx;
          color: #666;
          display: block;
          margin-bottom: 6rpx;
        }

        .detail-value {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
          display: block;
        }
      }
    }

    .gift-info {
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
      padding: 12rpx 20rpx;
      border-radius: 12rpx;
      border: 1rpx solid #ffcc02;

      .gift-icon {
        font-size: 28rpx;
        margin-right: 8rpx;
      }

      .gift-text {
        font-size: 26rpx;
        color: #ff8f00;
        font-weight: 500;
      }
    }
  }
  
  // 一行四个按钮的样式优化（已移至内联样式）
}
</style>